#include "edituserdlg.h"
#include "ui_edituserdlg.h"

#include <api/userapi.h>

EditUserDlg::EditUserDlg(int userId,QWidget *parent) :
    QDialog(parent),
    ui(new Ui::EditUserDlg)
{
    ui->setupUi(this);
    this->userId = userId;
    setWindowTitle(userId < 0 ? "添加用户" : "修改用户");
    QLabel *l = new QLabel;
    l->setText("备注");
    l->setAlignment(Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter);
    ui->gridLayout->addWidget(l,5,0);
    textEdit = new QTextEdit;
    ui->gridLayout->addWidget(textEdit,5,1,1,3);
    postBox = new MultiSelectComboBox;
    postBox->setMinimumHeight(35);
    ui->gridLayout->addWidget(postBox,4,1);
    roleBox = new MultiSelectComboBox;
    roleBox->setMinimumHeight(35);
    ui->gridLayout->addWidget(roleBox,4,3);
    initDlg();
    if(userId > 0){
        hideRow(ui->gridLayout,2,0);
    }
}

EditUserDlg::~EditUserDlg()
{
    delete ui;
}

void EditUserDlg::getParam(QList<TreeSelect> *deptTreeList,
                           QString initPassword,
                           QList<DictData> *dictDataList,
                           QList<DictData> *sexDataList)
{
    this->deptTreeList = deptTreeList;
    this->initPassword = initPassword;
    this->dictDataList = dictDataList;
    this->sexDataList = sexDataList;
    this->treeWidget = new QTreeWidget(this);
    treeWidget->setHeaderHidden(1);
    treeWidget->setMinimumSize(250,300);
    for(int i = 0;i< sexDataList->size();i++){
        ui->comboBox_editUser_sex->addItem(sexDataList->at(i).dictLabel,sexDataList->at(i).dictValue);
    }
    ui->radioButton_editUser_normal->setText(dictDataList->at(0).dictLabel);
    ui->radioButton_editUser_disable->setText(dictDataList->at(1).dictLabel);
    ui->lineEdit_editUser_pwd->setText(initPassword);
    for(int i = 0;i< deptTreeList->size();i++){
        QTreeWidgetItem *menu = new QTreeWidgetItem(treeWidget,
                            QStringList(deptTreeList->at(i).label));
        menu->setData(1,0,deptTreeList->at(i).id);
//        menu.setT
        QList<TreeSelect> list = deptTreeList->at(i).children;
        setDeptTree(&list,menu);
    }
    treeWidget->move(this->mapToParent(QPoint(0,0)).x() + 377,
                     this->mapToParent(QPoint(0,0)).y() + 47);
    connect(treeWidget,&QTreeWidget::clicked,this,&EditUserDlg::deptTreeClicked);
    treeWidget->close();
}



void EditUserDlg::initDlg()
{
    getUserById();
    for(int i = 0;i< posts.size();i++){
        postBox->addItem(posts.at(i).postName,posts.at(i).postId);
    }
    for(int i = 0;i< roles.size();i++){
        roleBox->addItem(roles.at(i).roleName,roles.at(i).roleId);
    }
    if(userId > 0){
        setUserInfo();
    }
}

void EditUserDlg::getUserById()
{
    UserApi userApi;
    QNetworkReply *reply = userApi.getById(userId);
    QByteArray bytes = reply->readAll().data();
    if(bytes.isEmpty()){
        QMessageBox::warning(this,"提示","服务器连接失败");
        return;
    }
    QJsonObject obj = QJsonDocument::fromJson(bytes).object();
    if(200 != obj.value("code").toInt()){
        QMessageBox::warning(this,"提示",obj.value("msg").toString());
        return;
    }
    QJsonArray roleArr = obj.value("roles").toArray();

    for(int i = 0;i< roleArr.size();i++){
        Role role = utils.getRole(roleArr.at(i).toObject());
        roles.append(role);
    }
    QJsonArray postArr = obj.value("posts").toArray();
    for(int i = 0;i< postArr.size();i++){
        Post post = utils.getPost(postArr.at(i).toObject());
        posts.append(post);
    }
    QJsonArray postIdsArr = obj.value("postIds").toArray();
    for(int i = 0;i< postIdsArr.size();i++){
        postIds.append(postIdsArr.at(i).toInt());
    }
    QJsonArray roleIdsArr = obj.value("roleIds").toArray();
    for(int i = 0;i< roleIdsArr.size();i++){
        roleIds.append(roleIdsArr.at(i).toInt());
    }
    if(userId > 0){
        user = utils.getUserByJsonObj(obj.value("user").toObject());
    }
}

void EditUserDlg::setUserInfo()
{
    ui->lineEdit_editUser_nickName->setText(user->nickName);
    ui->lineEdit_editUser_phone->setText(user->phonenumber);
    ui->comboBox_editUser_sex->setCurrentIndex(user->sex.toInt());
    //岗位
    for (int j = 0; j < postBox->popupModel->rowCount(); ++j) {
        for(int i = 0;i< postIds.size();i++){
            if(postBox->itemData(j).value<int>() == postIds.at(i)){
                postBox->popupModel->item(j)->setCheckState(Qt::Checked);
                QStandardItem* item=new QStandardItem(QIcon(":/image/res/close.jpg"),
                                postBox->itemText(j));
                postBox->selectModel->appendRow(item);
            }
        }
    }
    //角色
    for (int j = 0; j < roleBox->popupModel->rowCount(); ++j) {
        for(int i = 0;i< roleIds.size();i++){
            if(roleBox->itemData(j).value<int>() == roleIds.at(i)){
                roleBox->popupModel->item(j)->setCheckState(Qt::Checked);
                QStandardItem* item=new QStandardItem(QIcon(":/image/res/close.jpg"),
                                roleBox->itemText(j));
                roleBox->selectModel->appendRow(item);
            }
        }
    }
    textEdit->setText(user->remark);
    ui->btn_editUser_dept->setText(user->dept.deptName);
    ui->lineEdit_editUser_email->setText(user->email);
    user->status == "0" ? ui->radioButton_editUser_normal->setChecked(1)
                        : ui->radioButton_editUser_disable->setChecked(1);

}

void EditUserDlg::hideRow(QGridLayout *gridLayout, int row, bool bEnable)
{
    if(NULL == gridLayout) return;
    int columnCount = gridLayout->columnCount();
    for (int k = 0; k < columnCount;++k){
        QLayoutItem * item = gridLayout->itemAtPosition(row, k);
        if (item){
//            item->widget()->setEnabled(bEnable);
            item->widget()->setVisible(bEnable);
        }
    }
}

void EditUserDlg::setDeptTree(QList<TreeSelect> *treeList, QTreeWidgetItem *menu)
{
    for(int i = 0;i< treeList->size();i++){
        QTreeWidgetItem *childmenu = new QTreeWidgetItem(menu,
            QStringList(treeList->at(i).label));
        childmenu->setData(1,0,treeList->at(i).id);
        QList<TreeSelect> l = treeList->at(i).children;
        setDeptTree(&l,childmenu);
    }
    treeWidget->expandAll();
}

void EditUserDlg::deptTreeClicked()
{
    deptChangedFlag = 1;
    ui->btn_editUser_dept->setText(treeWidget->currentItem()->text(0));
}



void EditUserDlg::on_btn_cancle_clicked()
{
    this->close();
}


void EditUserDlg::on_btn_editUser_dept_clicked()
{
    treeWidget->setVisible(!treeWidget->isVisible());
}


void EditUserDlg::on_btn_ok_clicked()
{
    if(userId < 0){     //新增
        user = new User;
    }  //新增
    if(ui->lineEdit_editUser_nickName->text().isEmpty()){
        ui->lineEdit_editUser_nickName->setStyleSheet("border:1px solid red");
        return;
    }
    if(ui->lineEdit_editUser_username->text().isEmpty() && ui->lineEdit_editUser_username->isVisible()){
        ui->lineEdit_editUser_username->setStyleSheet("border:1px solid red");
        return;
    }
    user->nickName = ui->lineEdit_editUser_nickName->text();
    user->phonenumber = ui->lineEdit_editUser_phone->text();
    if(userId < 0){
        user->userName = ui->lineEdit_editUser_username->text();
    }
    user->sex = ui->comboBox_editUser_sex->currentIndex();
    if(postBox->selectModel->rowCount() > 0){
        for(int i = 0;i< postBox->selectModel->rowCount();i++){
            if(postBox->popupModel->item(i)->checkState()){
                user->postIds.append(postBox->itemData(i).value<int>());
            }
        }
    }
    user->remark = textEdit->toPlainText();
    if(deptChangedFlag){
        user->deptId = treeWidget->currentItem()->data(1,0).value<int>();
    }
    user->email = ui->lineEdit_editUser_email->text();
    if(ui->lineEdit_editUser_pwd->text().isEmpty() && ui->lineEdit_editUser_pwd->isVisible()){
        ui->lineEdit_editUser_pwd->setStyleSheet("border:1px solid red");
        return;
    }
    if(userId < 0){
        user->password = ui->lineEdit_editUser_pwd->text();
    }
    user->status = ui->radioButton_editUser_normal->isChecked() ? "0" : "1";
    if(roleBox->selectModel->rowCount() > 0){
        for(int i = 0;i< roleBox->popupModel->rowCount();i++){
            if(roleBox->popupModel->item(i)->checkState()){
                user->roleIds.append(roleBox->itemData(i).value<int>());
            }
        }
    }
    UserApi userApi;
    if(userId < 0){
        reply = userApi.addUser(user);
    }else{
        reply = userApi.updateUser(user);
    }
    QByteArray bytes = reply->readAll().data();
    if(bytes.isEmpty()){
        QMessageBox::warning(this,"提示","服务器连接失败");
        return;
    }
    QJsonObject obj = QJsonDocument::fromJson(bytes).object();
    QMessageBox::warning(this,"提示",obj.value("msg").toString());
    if(obj.value("code").toInt() == 200){
        this->close();
        emit addSuccess();
    }

}

